package cn.wangzg.viewpagerdemo;

import android.os.Bundle;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity3 extends AppCompatActivity {
    List<Fragment> fragments;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main3);
        OneFragment home = OneFragment.newInstance(R.color.red, "home");
        OneFragment msg = OneFragment.newInstance(R.color.yellow, "message");
        OneFragment mine = OneFragment.newInstance(R.color.blue, "mine");
        fragments=new ArrayList<>();
        fragments.add(home);
        fragments.add(msg);
        fragments.add(mine);
        ViewPager viewPager=findViewById(R.id.vp);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager(),1) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return "项目"+position;
            }
        });
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.home:
                        viewPager.setCurrentItem(0);
                        break;
                    case R.id.msg:
                        viewPager.setCurrentItem(1);
                        break;
                    case R.id.mine:
                        viewPager.setCurrentItem(2);
                        break;
                }
                return true;
            }
        });
        bottomNavigationView.setSelectedItemId(R.id.home);
    }
}